//
//  MainTabBarController.m
//  AffectionBee
//
//  Created by 李通 on 16/8/18.
//  Copyright © 2016年 chivalrous. All rights reserved.
//

#import "MainTabBarController.h"
#import "ShoppingViewController.h"
#import "HomeViewController.h"
#import "SupermarketViewController.h"
#import "MineViewController.h"
#import "TabBarButton.h"


@interface MainTabBarController ()<UITabBarControllerDelegate>

@property (nonatomic,strong)UIView *myTabBar;

@property (nonatomic,strong) RAMBadge *badge;
@property (nonatomic,copy) NSString *badgeValue;
@end

@implementation MainTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupChildVC];
    
    //接收来自超市的通知(加货物)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(GetSuperMarketNoti:) name:@"SuperMarketAddOne" object:nil];
    
    
    
    //接收来自超市的通知(减货物)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(GetSuperMarketNoti:) name:@"SuperMarketReduceOne" object:nil];
    
}
-(void)setupUI{
    self.delegate = self;
    // 隐藏之前的
    self.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.myTabBar = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenSize.height - self.tabBar.frame.size.height, kScreenSize.width,self.tabBar.frame.size.height)];
    self.myTabBar.backgroundColor = [UIColor colorWithRed:246/255.0 green:246/255.0 blue:246/255.0 alpha:1];
    [self.view addSubview:self.myTabBar];
    [self setupMyTabBar];
}
-(void)setupMyTabBar{
    
    NSArray *iconNames = @[@"v2_home", @"v2_order", @"shopCart",@"v2_my"];
    NSArray *selectedIconNames = @[@"v2_home_r", @"v2_order_r", @"shopCart_r", @"v2_my_r"];
    NSArray *titleNames = @[@"首页",@"闪电超市",@"购物车",@"我的"];
    
    //循环添加视图
    for (int i = 0; i<4; i++) {
        
        TabBarButton *button = [[TabBarButton alloc] initWithFrame:CGRectMake(i*(kScreenSize.width/4), 0, kScreenSize.width/4, self.myTabBar.frame.size.height)];
        
        [button addTarget:self action:@selector(changeVC:) forControlEvents:UIControlEventTouchUpInside];
        
        button.tag = i;
        
        NSString *title = titleNames[i];
        [button setTitle:title forState:UIControlStateNormal];
        
        NSString *normal = iconNames[i];
        [button setImage:[UIImage imageNamed:normal] forState:UIControlStateNormal];
        
        NSString *select =selectedIconNames[i];
        [button setImage:[UIImage imageNamed:select] forState:UIControlStateSelected];
        
        /*  将badge添加到tabBarButton上 默认设置为隐藏  */
        if (i == 2) {
            [self.badge addBadgeOnView:button];
            self.badge.hidden = YES;
        }
        if (i == 0) {  //默认第一个选中
            button.selected = YES;
        }else {
            button.selected = NO;
        }
        
        [_myTabBar addSubview:button];
    }
}

-(void)changeVC:(TabBarButton*)button{
    if(button.tag == 2){
        ShoppingViewController *shoppingController = [[ShoppingViewController alloc]init];
        shoppingController.title = @"购物车";
        //使用modal控制器效果来展示
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:shoppingController] animated:YES completion:nil];
    }else{
        [self animationWithButton:button];
        self.selectedIndex = button.tag;
    }
}

//为button添加动画
- (void)animationWithButton:(TabBarButton *)button {
    
    [self.myTabBar.subviews enumerateObjectsUsingBlock:^(__kindof UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[TabBarButton class]]) {
            obj.selected = NO;
        }
    }];
    button.selected = YES;
    CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    bounceAnimation.values = @[@1.0,@1.4,@0.9,@1.15,@0.95,@1.02,@1.0];
    bounceAnimation.duration = 0.25;
    bounceAnimation.calculationMode = kCAAnimationCubic;
    [button.imageView.layer addAnimation:bounceAnimation forKey:@"bounceAnimation"];
}

-(void)setupChildVC{
    HomeViewController *homeController = [[HomeViewController alloc]init];
    homeController.badgeValueBlock = ^(NSString *string){
        
        self.badgeValue = string;
    };
    [self addChildViewController:homeController title:@"首页" imgName:@"v2_home"];
    [self addChildViewController:[[SupermarketViewController alloc]init] title:@"闪电超市" imgName:@"v2_order"];
    [self addChildViewController:[UIViewController new] title:@"购物车" imgName:@"shopCart"];
    [self addChildViewController:[[MineViewController alloc] init] title:@"我的" imgName:@"v2_my"];
}
//MYMARK: - 设置tabBar的子控制器
- (void)addChildViewController:(UIViewController *)childController title:(NSString *)title imgName:(NSString *)imgName {
    childController.title = title;
    childController.view.backgroundColor = [UIColor whiteColor];
    childController.tabBarItem.image = [[UIImage imageNamed:imgName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childController.tabBarItem.selectedImage = [[UIImage imageNamed:[NSString stringWithFormat:@"%@_r",imgName]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [childController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} forState:UIControlStateSelected];
    [self addChildViewController:[[UINavigationController alloc]initWithRootViewController:childController]];
}


//MYMARK: - 拦截tabBar控制器的跳转
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    //取出当前控制器在所有tabBar的控制器中的下标
    NSArray *array = tabBarController.viewControllers;
    NSInteger index = [array indexOfObject:viewController];
    //如果是第三个控制器则返回NO
    if (index == 2) {
        
        return NO;
    }
    return YES;
}

/*  给badge赋值时如值为空则移除，若值非空则显示  */
- (void)setBadgeValue:(NSString *)badgeValue {
    
    if (badgeValue == nil) {
        [_badge removeFromSuperview];
        _badge = nil;
        return;
    }
    _badge.text = badgeValue;
    _badge.hidden = NO;
}

//MYMARK: - 懒加载badge控件
- (RAMBadge *)badge {
    
    if (_badge == nil) {
        
        _badge = [[RAMBadge alloc]initWithFrame:CGRectMake(0, 0, 15, 15)];
    }
    return _badge;
}

//当改变tabBar选中下标时为button添加动画
- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    [super setSelectedIndex:selectedIndex];
    TabBarButton *button = self.myTabBar.subviews[selectedIndex];
    [self animationWithButton:button];
}


//处理来自超市的通知
-(void)GetSuperMarketNoti:(NSNotification*)noti
{
    
    //取出购物车此时的商品数量
    NSInteger proNum = [self.badge.text integerValue];
    
    //加
    if ([noti.name isEqualToString:@"SuperMarketAddOne"])
    {
        //购物车添加商品数量
        proNum ++;
    }
    //减
    else if([noti.name isEqualToString:@"SuperMarketReduceOne"])
    {
        proNum --;
    }
    
    self.badgeValue = [NSString stringWithFormat:@"%ld",(long)proNum];
    
    //判断是否为0
    if (proNum == 0)
    {
        self.badge.hidden = YES;
    }
}




//移除通知者
-(void)dealloc
{
     [[NSNotificationCenter defaultCenter]removeObserver:self];
}



//更改状态栏颜色
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
